/*
 * sound.c
 */
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>
//#include"fft.h"
#define LENGTH 10    /* 存储秒数 */
#define RATE 44100   /* 采样频率 */
#define SIZE 16      /* 量化位数 */
#define CHANNELS 2  /* 声道数目 */
/* 用于保存数字音频数据的内存缓冲区 */

unsigned char buf[LENGTH*RATE*SIZE*CHANNELS/8];
//unsigned char buf[8000];
int main()
{
  int fd;	/* 声音设备的文件描述符 */
  int fd_music;
  int arg;	/* 用于ioctl调用的参数 */
  int status;   /* 系统调用的返回值 */
  int i = 0;
  int value = 0;
  int level = 0;

  /* 打开声音设备 */
  fd = open("/dev/dsp", O_RDWR);
  if (fd < 0) {
    perror("open of /dev/dsp failed");
    exit(1);
  }
  /* 设置采样时的量化位数 */
  arg = SIZE;
  status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
  if (status == -1)
    perror("SOUND_PCM_WRITE_BITS ioctl failed");
  if (arg != SIZE)
    perror("unable to set sample size");
  /* 设置采样时的声道数目 */
  arg = CHANNELS; 
  status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
  if (status == -1)
    perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
  if (arg != CHANNELS)
    perror("unable to set number of channels");
  /* 设置采样时的采样频率 */
  arg = RATE;
  status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
  if (status == -1)
    perror("SOUND_PCM_WRITE_WRITE ioctl failed");
  /* 循环，直到按下Control-C */
 while (1) {
   printf("Say something:\n");
    status = read(fd, buf, sizeof(buf)); /* 录音 */
    if (status != sizeof(buf))
      perror("read wrong number of bytes");

   fd_music = creat("music", 0664);
   status = write(fd_music, buf, sizeof(buf) );
       if (status != sizeof(buf))
      perror("can't write file\n");
   status = close( fd_music );
   if(status == -1)
   perror("can't close file\n");

 /*
  for(i=0;i<4000;i++)                           //求变换后结果的模值，存入复数的实部部分
	{	
		value+=buf[i]*buf[i];
	}
level = value / 4000;
printf("%d\n",level-16000 );               //输出声音烈度
value = 0;
*/

    printf("You said:\n");
    status = write(fd, buf, sizeof(buf)); // 回放 
    if (status != sizeof(buf))
      perror("wrote wrong number of bytes");
/*
    // 在继续录音前等待回放结束 
    status = ioctl(fd, SOUND_PCM_SYNC, 0); 
    if (status == -1)
      perror("SOUND_PCM_SYNC ioctl failed");
*/
  return 0;
  }

}
